<?php 
namespace app\task\controller;
use app\BaseController;
use think\facade\Db;
use app\common\lib\WxTemplateMsg;
class ArticlePlanWxMsg extends BaseController
{
    //获取计划里发送数量不足的计划发送模板消息
    public function checkPlanArticle(){
        $template_id=2;//消息模板id
        $pushPlans = \app\common\model\PushPlan::where('is_open', 1)
            ->where('number_of_articles', '>', 0)
            //->where('member_id', '=', 4)//==============================================正式使用后这里需要删除
            ->select();
        foreach ($pushPlans as $plan) {
            //该计划对应的栏目里的文章数量统计
            $planArticleCount=Db::name("article")->where([
                ["state","=",2],//待发布的
                ["article_class_id","=",$plan['article_class_id']]
            ])->count();
            //判断文章数量是否小于20条
            if($planArticleCount<20){
                //判断同一消息模板有没有5天内发过，如果发过就不发了（防止第天发送，骚扰）
                $fiveDaysAgoTimestamp = strtotime("-5 days", time());
                $msgCount = \app\common\model\TemplateMessageRecording::where('message_template_id',$template_id)
                    ->where('create_time', '>',$fiveDaysAgoTimestamp)
                    ->where('member_id', '=', $plan->member_id)
                    ->where('content', 'like', "%".$plan->name."%")
                    ->count();
                if($msgCount){
                    continue;
                }else{
                    //发送模板消息
                    $result=WxTemplateMsg::send($plan->member_id,$template_id, [
                        'thing17' => "文章库不足提醒",
                        'thing35' => "对应的文章数量{$planArticleCount}条",
                        'thing4' => $plan->name,
                    ]);  
                    echo "plan_id".$plan->id."发送模板消息 ";
                }
            }

        }
    }

}
